package com.fivefaces.ide.plugins.impl;

import com.fivefaces.ide.plugins.CommandBuilder;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 * User: imrank
 * Date: 13/04/11
 * Time: 11:19 AM
 */
public class MacCommandBuilder implements CommandBuilder {

    public String[] buildCommand(String filePath) {
        return new String[]{writeScriptFile(filePath)};
    }

    private String writeScriptFile(String path) {
        String result = null;
        FileWriter fileWriter = null;
        try {
            String tempDir = System.getProperty("java.io.tmpdir");
            File executeFile = new File(tempDir + File.separator + new Date().getTime() + ".sh");
            fileWriter = new FileWriter(executeFile);
            fileWriter.write("#!/bin/sh\n");
            fileWriter.write("osascript -e 'tell application \"terminal\"' -e \"do script \\\"cd " + path + "\\\"\" -e 'activate' -e 'end tell'");
            result = executeFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        makeFileExecutable(result);
        return result;
    }

    private void makeFileExecutable(String result) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("chmod", "a+x", result);
            processBuilder.redirectErrorStream();
            processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
